package com.sx.micowell.framework.model

import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.example.mvvm.base.data.MutableLiveListData
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.rx.RxTimer
import com.example.mvvm.until.LogUtils
import com.github.mikephil.charting.data.Entry
import com.google.gson.Gson
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.service.IApiService
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.request.SportEndBeanItem
import com.miloyu.modelnet.response.SportEndResponse
import com.miloyu.modelnet.response.TrainSelectData
import com.miloyu.modelnet.response.log
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.entity.PlanSettingBean
import com.sx.micowell.framework.serialPort.ByteUtil
import com.sx.micowell.framework.tools.CalcuUtils
import com.sx.micowell.framework.tools.cmd.CmdException
import com.sx.micowell.module.sport.SportReceive
import com.sx.widget.view.CountDownUtils
import java.math.BigDecimal

/**
 * @Description 运动
 * @Author 梁浩文
 * @Date 2021/9/1 17:16
 */
class SportModel : BaseViewModel() {
    @JvmField
    var sportList: MutableLiveListData<SportReceive> = MutableLiveListData()

    //0速度 1力矩
    var chartTypeY: Int = 0

    var errorFinishEvent: MutableLiveData<Boolean> = MutableLiveData()

    var cmdExceptions: MutableList<CmdException>? = null

    var selectData: MutableList<TrainSelectData>? = null

    var accumulativeCaloriesLiveData = ObservableField<String>("0")    //累计卡路里

    var lineListData = mutableListOf<Entry>()  //线性图

    var planSettingBean: PlanSettingBean? = null

    var modeLiveData = ObservableField<String>()  //模式

    var powerLiveData = ObservableField<String>() //力量kg

    var currentCount = MutableLiveData<Int>(0) //当前次数

    var currentAction = MutableLiveData<Int>(0) //当前动作

    var currentGroup = MutableLiveData<Int>(0) //当前组

    var currentPlace = MutableLiveData<Int>(0)  //当前部位

    var allGroup = ObservableField<Int>(0) //组数

    var allCount = ObservableField<Int>(0)  //次数

    var allPlace = ObservableField<Int>(0)  //部位总数

    var allPower = ObservableField<Int>(0)  //力量

    var consumeTime = MutableLiveData<Long>(0L)   //总时长

    var currentActionCount = ObservableField<Int>(0)

    var uiConsumeTime = ObservableField<String>("00:00:00")

    var placeConsumeCalories = mutableMapOf<Int, SportEndBeanItem>()

    var finishEvent = MutableLiveData<Boolean>(false)

    //事件
    var changeVideoUrlEvent = MutableLiveData<String>()

    var sendEvent = MutableLiveData<Long>()
    fun getVideo(): PlanSettingBean? {
        if (planSettingBean == null) {
            selectData?.let {
                var indexOf = it.indexOf(TrainSelectData(1028))
                if (indexOf != -1) {
                    var body = it.get(indexOf) as TrainSelectData
                    planSettingBean =
                        Gson().fromJson(Gson().toJson(body.child), PlanSettingBean::class.java)
                }
            }
            planSettingBean?.let {
                allCount.set(it.count)
                allGroup.set(it.num)
                allPower.set(it.power)
                allPlace.set(it.selectBean.size)
                currentActionCount.set(it.selectBean[0].categoryUrl.split(",").size - 1)
            }
        }

        return planSettingBean
    }

    fun initVideo() {
        getVideo()?.let {
            var categoryUrl = it.selectBean.get(0).categoryUrl
            if (!TextUtils.isEmpty(categoryUrl)) {
                changeVideoUrlEvent.postValue(categoryUrl.split(",")[0])
            }

        }
    }

    fun finishSport() {
        HttpClient.instance.create(IApiService::class.java)
            .sportEnd(placeConsumeCalories.values.toList())
            .compose(RxUtils.compose())
            .doOnSubscribe {
                ui.showDialog()
            }
            .subscribe(object : ApiResponse<SportEndResponse>() {
                override fun success(data: SportEndResponse?, msg: String?) {
                    ui.hideDialog()
                    context.startContainerFragment(
                        RouteManager.getInstance()
                            .getSportEndFragment(data!!.calorie, data.duration)
                    )
                    context.finish()
                }

                override fun onFail(e: Throwable?, errorMsg: String?) {
                    ui.hideDialog()
                    errorFinishEvent.postValue(true)
                }

            })
    }


    //叠加卡路里
    fun cacheCalories(calories: BigDecimal) {
        getVideo()?.let {
            if (it.selectBean.size > currentPlace.value as Int) {
                var placeId = it.selectBean.get(currentPlace.value as Int).id
                var sportEnd = SportEndBeanItem(placeId)
                if (placeConsumeCalories.containsKey(placeId)) {
                    sportEnd = placeConsumeCalories.get(placeId)!!
                }
                sportEnd.powerKg = allPower.get().toString()
                sportEnd.calorie = CalcuUtils.getInstance().add(
                    sportEnd.calorie!!.toBigDecimal(),
                    calories,
                    4
                ).toInt()
                var timeValue = consumeTime.value!!.toInt()
                if (timeValue != 0) {
                    timeValue = timeValue / 60
                }
                sportEnd.duration = timeValue
                placeConsumeCalories[placeId] = sportEnd
            }

        }

        accumulativeCaloriesLiveData.set(
            accumulativeCaloriesLiveData.get()!!.toBigDecimal().add(
                calories
            ).setScale(
                2,
                BigDecimal.ROUND_HALF_UP
            ).toPlainString()
        )
    }

    //添加次数
    fun addCurrentCount() {
        var value = finishEvent.value as Boolean
        if (!value) {
            var count = currentCount.value as Int
            if (getVideo()!!.selectBean.size > currentPlace.value as Int) {
                var categoryUrl = getVideo()!!.selectBean.get(currentPlace.value as Int).categoryUrl
                var split = categoryUrl.split(",")
                currentActionCount.set(split.size - 1)
            }
            if (count >= allCount.get()!!) {
                addCurrentAction()
            } else if (count + 1 == allCount.get()!!) {
                var action = currentAction.value as Int
                currentAction.value = action + 1
                currentCount.value = count + 1
            } else {
                currentCount.value = count + 1
            }
        }
    }

    //添加动作
    private fun addCurrentAction() {

        var action = currentAction.value as Int
        //获取当前动作数量
        //todo
        if (getVideo()!!.selectBean.size > currentPlace.value as Int) {
            var categoryUrl = getVideo()!!.selectBean.get(currentPlace.value as Int).categoryUrl
            var split = categoryUrl.split(",")
            if (action >= split.size - 1) {
                LogUtils.d("addCurrentAction1")
                addCurrentGroup()
            } else {
                LogUtils.d("addCurrentAction2")
                currentCount.value = 1
                changeVideoUrlEvent.value = split[action]
            }
        } else {
            LogUtils.d("addCurrentAction3${getVideo()!!.selectBean.size}---${currentGroup.value as Int}")
            addCurrentGroup()
        }
    }


    //添加组数
    private fun addCurrentGroup() {
        "addCurrentGroup".log()
        var group = currentGroup.value as Int
        if ((group + 1) >= allGroup.get()!!) {
            addCurrentPlace()
            LogUtils.d("addCurrentGroup1")
        } else {
            currentCount.value = +1
            currentAction.value = 0
            currentGroup.value = group + 1
            LogUtils.d("addCurrentGroup2")
        }
    }

    //添加部位
    private fun addCurrentPlace() {
        "addCurrentPlace".log()
        var place = currentPlace.value as Int
        if ((place + 1) >= allPlace.get()!!) {
            //完成
            finishEvent.value = true
            currentCount.value = allCount.get()
            currentAction.value = currentActionCount.get()
            currentGroup.value = allGroup.get()
            currentPlace.value = allPlace.get()
            LogUtils.d("addCurrentPlace1")
        } else {
            currentCount.value = 1
            currentAction.value = 0
            currentGroup.value = 0
            currentPlace.value = place + 1
            LogUtils.d("addCurrentPlace2")

        }
    }

    //获取拉力模式
    fun getMode(): Int {
        selectData?.let {
            if (TextUtils.isEmpty(powerLiveData.get())) {
                var split = (it.get(it.indexOf(TrainSelectData(1015))).child as String).split("&")
                powerLiveData.set(split[0])
            }
            return ByteUtil.hexStrToTenInteger(powerLiveData.get())
        }
        return 0
    }

    fun getModeType(): Int {
        selectData?.let {
            var mode = (it.get(it.indexOf(TrainSelectData(1015))).child as String).split("&")[0]
            //00：恒等张力
            //01：观察着模式
            //02：力量递增模式
            //03：力量递减模式
            //04：极限挑战模式
            //05：划船模式
            //06：链条模式
            //07：高尔夫模式
            //08：力矩标定模式
            mode.log()
            when (mode) {
                "00" -> {
                    chartTypeY = 0
                    modeLiveData.set("恒等张力")
                    return IntentKey.OBSERVE
                }
                "01" -> {
                    // 观察着模式
                    chartTypeY = 1
                    modeLiveData.set("观察者模式")
                    return IntentKey.OBSERVE
                }
                "04" -> {
                    chartTypeY = 1
                    modeLiveData.set("极限挑战模式")
                    return IntentKey.LINE_MODE
                }
                "05" -> {
                    chartTypeY = 1
                    modeLiveData.set("划船模式")
                    return IntentKey.LINE_MODE
                }
                "06" -> {
                    chartTypeY = 0
                    modeLiveData.set("链条模式")
                    return IntentKey.LINE_MODE
                }
                "07" -> {
                    chartTypeY = 0
                    modeLiveData.set("高尔夫模式")
                    return IntentKey.LINE_MODE
                }
                "02" -> {
                    //力量递增 递减
                    chartTypeY = 1
                    modeLiveData.set("力量递增模式")
                    return IntentKey.POWER
                }
                "03" -> {
                    chartTypeY = 1
                    modeLiveData.set("力量递减模式")
                    return IntentKey.POWER
                }
                "08" -> {
                    chartTypeY = 1
                    modeLiveData.set("力矩标定模式")
                }
                else -> {
                    return IntentKey.OBSERVE
                }
            }

        }
        return IntentKey.OBSERVE
    }

    //获取kg
    fun getPower(): MutableList<Int> {
        var power = getVideo()!!.power as Int * 10
        //转换高低位
        var short = ByteUtil.getShort(ByteUtil.getTenToHex(power))
        var low8 = short.substring(0, 2)
        var height8 = short.substring(2, 4)
        var mutableListOf = mutableListOf<Int>()
        mutableListOf.add(ByteUtil.hexStrToTenInteger(height8))
        mutableListOf.add(ByteUtil.hexStrToTenInteger(low8))
        return mutableListOf;
    }


    var rxTimer = RxTimer()
    var serialTimer = RxTimer()
    override fun registerRxBus() {
        super.registerRxBus()
        rxTimer.interval(1000, object : RxTimer.RxAction {
            override fun action(number: Long) {
                consumeTime.value = number
                var time = CountDownUtils.initData(number)
                uiConsumeTime.set(time)
            }
        })
        serialTimer.interval(500, object : RxTimer.RxAction {
            override fun action(number: Long) {
                sendEvent.value = number
            }

        })

    }

    override fun onDestroy() {
        super.onDestroy()
        rxTimer?.let {
            it.cancel()
        }
        serialTimer?.let {
            it.cancel()
        }
    }
}

